﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.DeviceManage.Project;
using ProduceBasicData.Api.DTO.DeviceDto.ProjectDto;
using ProduceBasicData.Domain.DeviceManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.DeviceManage.Project
{
    /// <summary>
    /// 获取项目维护信息处理器
    /// </summary>
    public class GetProjectFormRelationHandler : IRequestHandler<GetProjectFormRelationCommand, ApiResult<List<ProjectMaintenanceDto>>>
    {
        private readonly IBaseRespository<ProjectMaintenance> _projectMaintenanceRepository;
        private readonly IBaseRespository<ProjectFormRelation> _projectFormRelationRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="projectMaintenanceRepository"></param>
        /// <param name="projectFormRelationRepository"></param>`
        /// <param name="mapper"></param>
        public GetProjectFormRelationHandler(IBaseRespository<ProjectMaintenance> projectMaintenanceRepository, IBaseRespository<ProjectFormRelation> projectFormRelationRepository, IMapper mapper)
        {
            _projectMaintenanceRepository = projectMaintenanceRepository;
            _projectFormRelationRepository = projectFormRelationRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理：根据表单ID查询所有关联的项目维护信息
        /// </summary>
        public async Task<ApiResult<List<ProjectMaintenanceDto>>> Handle(GetProjectFormRelationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 1. 校验请求参数（表单ID必须大于0）
                if (request.FormId <= 0)
                {
                    return new ApiResult<List<ProjectMaintenanceDto>>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "表单ID不能为空",
                        Data = new List<ProjectMaintenanceDto>()
                    };
                }

                // 2. 构建查询：查询指定表单下所有未删除的关联项目
                var query = from relation in _projectFormRelationRepository.GetAll()
                            join project in _projectMaintenanceRepository.GetAll()
                              on relation.ProjectId equals project.Id
                            where relation.FormId == request.FormId   // 按表单ID筛选
                                  && relation.Isdel == false         // 排除已删除的关联
                                  && project.Isdel == false          // 排除已删除的项目
                            select project;

                // 3. 执行查询并映射为DTO
                var projectList = await query.ToListAsync(cancellationToken);
                var resultDto = _mapper.Map<List<ProjectMaintenanceDto>>(projectList);

                return new ApiResult<List<ProjectMaintenanceDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = resultDto
                };
            }
            catch (Exception ex)
            {
                // 实际项目中建议添加日志记录
                return new ApiResult<List<ProjectMaintenanceDto>>
                {
                    Code = ApiEnum.Failed,
                    Msg = $"查询异常：{ex.Message}",
                    Data = new List<ProjectMaintenanceDto>()
                };
            }
        }
    }
}
